using System;
using System.Collections.Generic;
using System.Text;
using JobShopModel.Model.FactoryLvl;
using JobShopModel.Model.JobLvl;
using JobShopModel.Model.Station;
using JobShopModel.Model;

namespace JobShopModel.Events
{
    /// <summary>
    /// Event that is raised when a job is completed (arrives back at the IOStation)
    /// </summary>
    public class EndJob : StationEvent
    {

        private Job currentJob;

        /// <summary>
        /// Default COnstructor
        /// </summary>
        /// <param name="sTime"> Time the Event is excecuted</param>
        /// <param name="currentJob">Job being terminated</param>
        public EndJob(Time sTime, Job currentJob)
            : base(sTime, StationsName.IOSTATION)
        {
            this.currentJob = currentJob;
        }

        /// <summary>
        /// Polymorphic method
        /// It will be instanced by all Events and excecuted by the eventloop
        /// </summary>
        public override void Process()
        {
            Factory fact = Factory.getInstance();
            Time elapsedTime = new Time();

            //End the Job
            StationIO endStation = (StationIO)fact.Stations[StationName];
            currentJob.FinishTime = fact.CurrentTime;

            currentJob.CurrentOperation.Terminate();

            //Update the statistics ofr jobs in general
            JobStats stats = fact.JobStatistics;

            stats.JobCounter[currentJob.Type]++;
            stats.TotalDelayFifoTransp[currentJob.Type] += currentJob.TotalWaitingFifo;
            stats.TotalDelayQueueStation[currentJob.Type] += currentJob.TotalQueueTime;
            stats.TotalTransporterDelay[currentJob.Type] += currentJob.TotaBlockedTime;
            
            //Compute new average
            stats.CalculateAverage(currentJob.Type);

            Logger.InsertElement(new LogItem(ItemPriorities.URGENT,fact.CurrentTime,currentJob+" is finished"));


        }

        /// <summary>
        /// Comparison operator (for IComparable)
        /// </summary>
        /// <param name="event1">First event</param>
        /// <param name="event2">Second event</param>
        /// <returns>Returns -1 if event1 occurs first, 1 if event2 occurs first, 0 if the times are the same</returns>
        public override int CompareTo(IEvent event1, IEvent event2)
        {
            if (event1.ExecTime < event2.ExecTime)
                return -1;
            else if (event1.ExecTime > event2.ExecTime)
                return 1;
            else
                return 0;
        }

        public override string ToString()
        {
            return "EndJob, execTime: "+ExecTime;
        }
    }
}
